import {
    ActionType,
    FooterToolbar,
    PageContainer,
    ProColumns,
    ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Drawer, Form, FormInstance, message, Popconfirm } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { deleteApi,  selectListApi, updateApi } from './services';
import { history, Link } from '@umijs/max';
import { getEnumsApi } from '@/services/demo';




const TableList: React.FC<unknown> = () => {
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const editFormRef = useRef<FormInstance>();
    const [currentItem, setCurrentItem] = useState<any>(null)
    const [enums, setEnums] = useState<Record<string, any>>({})

    useEffect(() => {
        getEnums()
    }, [])
    const getEnums = async () => {
        const res = await getEnumsApi({
            categories: {},
            // tags:{}
        })
        if (res.code == 200) {
            const categories:Record<number,any> = {}; 
            res.data.categories.forEach((item:any)=>{
                categories[item.value]=item.name;
            }) 

            setEnums({...res.data,categories})

        }
    }

    const deleteItem = async (id: number) => {
        const res = await deleteApi(id)
        if (res.code == 200) {
            message.success("删除成功")
            actionRef.current?.reload()
        }
    }

    const columns: ProColumns<any>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            sorter: true,
            hideInSearch: true,
            render: (_, item) => {
                return <Link style={{ display: "block" }} to={`/article/detail/${item.id}`} >{item.id}</Link>

            }

        },
        {
            title: '标题',
            dataIndex: 'title',
            tip: '名称是唯一的 key',
            sorter: true,

            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '名称为必填项',
                    },
                ],
            },
        },
        {
            title: '分类',
            dataIndex: 'categoryId',
            valueType: 'text',
            sorter: true,
            valueEnum: enums.categories,

        },
        {
            title: '摘要',
            dataIndex: 'comment',
            valueType: 'text',


        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            hideInForm: true,
            hideInSearch: true,
            sorter: true

        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            hideInForm: true,
            hideInSearch: true

        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <Popconfirm
                        title="删除"
                        description="确定删除当前分类？"

                        onConfirm={() => { deleteItem(record.id) }}
                    >
                        <Button danger>删除</Button>
                    </Popconfirm>


                </>
            ),
        },
    ];

    useEffect(() => {
        if (createModalVisible && currentItem) {
            editFormRef.current?.setFieldsValue(currentItem)
        } else if (createModalVisible) {
            editFormRef.current?.resetFields()
        }
    }, [createModalVisible])


    return (
        <PageContainer
            header={{
                title: '文章查询',
            }}
        >
            <ProTable<any>
                headerTitle="查询表格"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        key="1"
                        type="primary"
                        onClick={() => history.push('/article/add')}
                    >
                        新建
                    </Button>,
                ]}
                request={async (params, sorter, filter) => {
                    console.log(params, sorter, filter);
                    let orderBy = 'id desc';
                    const objArr = Object.keys(sorter);
                    // 有排序字段,暂时支持单字段
                    if (objArr.length > 0) {
                        const file = objArr[0];
                        if (sorter[file] == "descend") {
                            orderBy = `${file} desc`
                        } else {
                            orderBy = `${file} asc`
                        }
                    }

                    const { current, pageSize, ...other } = params
                    const { data, code } = await selectListApi({
                        page: current,
                        pageSize: pageSize,
                        orderBy,
                        ...other

                    });
                    return {
                        data: data?.list || [],
                        success: code == 200,
                        total: data.total || 0
                    };
                }}
                columns={columns}
                pagination={{
                    pageSize: 10,
                    onChange: (page) => console.log(page),
                }}
            />

        </PageContainer>
    );
};

export default TableList;
